using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using IGlobalist.Cms.Common;
using IGlobalist.Cms.Bll;
using IGlobalist.Cms.Model;
using IGlobalist.Cms.Presentation;
using System.Diagnostics;

namespace IGlobalist.Cms
{
    public partial class VideoAdd : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                long pageID = Convert.ToInt64(Request["pageID"]);
                IPage page = PageController.GetPageCurrent(pageID);
                ContentCategoryList catlist = page.CategoryList;
                ddlCategory.Items.Clear();
                ddlCategory.Items.Add(new ListItem("Root", "0"));
                foreach (Category c in catlist)
                {
                    ddlCategory.Items.Add(new ListItem(c.Name, c.ID.ToString()));
                }

                if ((Request["del"] == "1") && (Request["id"] != null))
                {
                    long pid = 0, cid = 0;
                    DeleteVideo(Convert.ToInt64(Request["id"]));
                    pid = Convert.ToInt64(Request["pid"]);
                    cid = Convert.ToInt64(Request["cid"]);
                    string path = pid + "_" + cid + "_" + Request["id"] + "/default.aspx?video=1";
                    Response.Redirect(path);

                }
                #region rate

                if ((Request["rate"] == "1") && (Request["id"] != null))
                {
                    IList<ListItem> listRate = new List<ListItem>();
                    
                    bool rate=true;
                    if (Session["Rate"] != null)
                    {
                        listRate = (IList<ListItem>)Session["Rate"];
                    }
                    for (int i = 0; i < listRate.Count; i++)
                    {
                        if ((listRate[i].Text==Convert.ToString(Request["id"]))&& (listRate[i].Value==IGlobalistMembership.GetUser().ID.ToString()))
                        {
                            rate=false;
                            break;
                        }
                    }
                    
                    if(rate==true)
                    {
                        Video video = VideoController.GetVideo(Convert.ToInt64(Request["id"]));
                        if (Convert.ToInt32(Request["p"]) > 0)
                            video.Rates = video.Rates + Convert.ToInt32(Request["p"]);
                        VideoController.UpdateVideo(video);
                        listRate.Add(new ListItem(Convert.ToString(Request["id"]), IGlobalistMembership.GetUser().ID.ToString()));
                        Session["Rate"] = listRate;
                    }
                    long pid = 0,cid=0;
                    pid = Convert.ToInt64(Request["pid"]);
                    cid = Convert.ToInt64(Request["cid"]);
                    string path = pid + "_" + cid + "_" + Request["id"] + "/default.aspx";
                    Response.Redirect(path);
                }
                #endregion

                if ((Request["edit"] == "1") && (Request["id"] != null))
                {
                    long id = Convert.ToInt64(Request["id"]);
                    EditVideo(id);

                }

                #region addcomment
                if (Request["comment"]!=null)
                {
                    long pid = 0, cid = 0;
                    if (Request["pid"]!=null)
                        pid =Convert.ToInt64(Request["pid"]);
                    if (Request["cid"] != null)
                        cid = Convert.ToInt64(Request["cid"]);
                    AddComment(Convert.ToInt64(Request["id"]), Convert.ToString(Request["comment"]), pid, cid);
                }
                #endregion
            }
        }

        private void EditVideo(long id)
        {
            ddlClassPage.Enabled= false;
            Video video = VideoController.GetVideo(id);
            ViewState["GetVideo"] = video;
            hdfVideoID.Value = video.ID.ToString();
            ddlCategory.SelectedValue = video.CategoryID.ToString();
            tbName.Text = video.Name;
            tbTag.Text = video.Tags;
            tbDescription.Text = video.Description;            
            lbFile.Enabled = false;
            fuFile.Enabled = false;
        }

        private void AddComment(long id, string data, long pid, long cid)
        {
             ICmsClass clazzObject= new CmsClass();
            if (Session["ClassVideoId"] != null)
            {
                clazzObject = (CmsClass)Session["ClassVideoId"];
            }
            else
            {
                IList<ICmsClass> cList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.ContentNote);
              
                foreach (ICmsClass clazz in cList)
                {
                    for (int i = 0; i < clazz.PropertyList.Count; i++)
                        if ((Convert.ToString(clazz.PropertyList[i].Name) == "Type") && (Convert.ToString(clazz.PropertyList[i].Value) == "Video"))
                        {
                            clazzObject=clazz;
                            //classId = clazz.ID;
                            Session["ClassVideoId"] = clazz;
                            break;
                        }
                }
            }
            ContentNoteList cnoteList = new ContentNoteList();
            Video video = new Video();
            if (id > 0 && data != "")
            {
                video = VideoController.GetVideo(id);
                ContentNote cnote = new ContentNote();
                cnoteList= video.NoteList;

                cnote.Class=clazzObject;
                cnote.ClassID=clazzObject.ID;
                cnote.ClassTypeID=Convert.ToInt16(CmsObjectType.ContentNote);
                cnote.ActionType = ActionType.Add;
                cnote.Author = IGlobalistMembership.GetUser().ID;
                cnote.CreatedDate = DateTime.Now;
                cnote.Description = data;
                cnoteList.Add(cnote);

                VideoController.UpdateVideo(video); 
            }

            string path = pid + "_" + cid + "_" + id + "/default.aspx?video=1";
            Response.Redirect(path);

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {

            long id = 0;// Convert.ToInt64(hdfVideoID.Value);
            Video video = new Video();
            if (ViewState["GetVideo"]!=null)
            {
                video = (Video)ViewState["GetVideo"];
                video.Name = tbName.Text+ " ";
                video.Tags = tbTag.Text;
                video.CategoryID = Convert.ToInt64(ddlCategory.SelectedValue);
                video.Description = tbDescription.Text;
                video.EditedBy = IGlobalistMembership.GetUser().ID;
                video.EditedDate = DateTime.Now;
                VideoController.UpdateVideo(video);
                ltrScript.Text = "<script>window.close();window.opener.location.reload();</script>";
            }           
            else
            {
                ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
                video.ClassTypeID = clazz.ClassTypeID;
                video.Class = clazz;
                video.ClassID = clazz.ID;
                video.Name = tbName.Text + " ";
                video.Tags = tbTag.Text;
                video.CategoryID = Convert.ToInt64(ddlCategory.SelectedValue);
                video.Description = tbDescription.Text;
                video.Author = IGlobalistMembership.GetUser().ID;
                video.CreatedDate = DateTime.Now;
                video.Sharing = false;
                video.Rates = 1;
                video.Views = 1;
                video.FileName = fuFile.FileName;
                

                if (!string.IsNullOrEmpty(fuFile.FileName))
                {
                    id = VideoController.InsertVideo(video);
                    string path = "";
                    string fExtention = "";
                    try
                    {
                        path = Path.Combine(DataRootPhysicalPath, "Videos");
                        HttpPostedFile fPost = fuFile.PostedFile;
                        string fName = fuFile.FileName;
                        fExtention = Path.GetExtension(fPost.FileName);
                        fPost.SaveAs(Path.Combine(path, id + fExtention));

                        Process p = new Process();
                        p.StartInfo.FileName = Server.MapPath("ffmpeg/ffmpeg.exe");
                        p.StartInfo.CreateNoWindow = true;
                        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        p.StartInfo.Arguments = "-i " + Path.Combine(path, id + fExtention) + " " + Path.Combine(path, id + ".flv");
                        p.Start();
                        lblError.Text = "";


                        //thunbnail
                        Process pfig = new Process();
                        pfig.StartInfo.FileName = Server.MapPath("ffmpeg/ffmpeg.exe");
                        pfig.StartInfo.CreateNoWindow = true;
                        pfig.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        pfig.StartInfo.Arguments = "-i " + Path.Combine(path, id + fExtention) + " -an -r 1 -y -s 120x100 -vframes 1 " + Path.Combine(path, "%d"+id+".jpg");
                        //pfig.StartInfo.Arguments = "-i " + Path.Combine(path, id + fExtention) + " -y -ss 00:00:00 -vframes 1 -an -sameq -pix_fmt rgb24 -f gif " + Path.Combine(path, id + ".gif");
                        pfig.Start();

                        //convert finish-> del file source
                        FileInfo fileInfo= new FileInfo(Path.Combine(path, id + fExtention));
                        fileInfo.Delete();
                        fileInfo = new FileInfo(Path.Combine(path, id + ".flv"));

                        if (fileInfo.Length < 1)
                        {
                            DeleteVideo(id);
                        }
                        else
                        {
                            video = VideoController.GetVideo(id);
                            video.Sharing = true;
                            VideoController.UpdateVideo(video);
                        }

                    }
                    catch { }

                    ltrScript.Text = "<script>window.close();window.opener.location.reload();</script>";

                }
                else
                    lblError.Text = "Selected file video. ";
            }
            
        }

        private void DeleteVideo(long id)
        {
            VideoController.DeleteVideo(id);

            //delete file
            string path = "";
            path = Path.Combine(DataRootPhysicalPath, "Videos");
            FileInfo fileInfo = new FileInfo(Path.Combine(path, id + ".flv"));
            fileInfo.Delete();
            fileInfo = new FileInfo(Path.Combine(path,"1" + id + ".jpg"));
            fileInfo.Delete();
        }
    }
 }
